<?php

namespace app\command;

use Workerman\Worker;
use think\console\Input;
use think\console\Output;
use GatewayWorker\Gateway;
use think\console\Command;
use GatewayWorker\Register;
use think\console\input\Option;
use GatewayWorker\BusinessWorker;
use think\console\input\Argument;

class LinuxWork extends Command
{
    protected function configure()
    {
        $this->setName('linuxwork')
            ->addArgument('action', Argument::OPTIONAL, 'start|stop|restart|reload|status|connections', 'start')
            ->addOption('daemon', 'd', Option::VALUE_NONE, 'run the server in daemon mode')
            ->setDescription('GatewayWorker Server');
    }

    protected function execute(Input $input, Output $output)
    {
        if(!extension_loaded('pcntl'))
        {
            exit("请安装pcntl扩展\n");
        }
        if(!extension_loaded('posix'))
        {
            exit("请安装posix扩展\n");
        }
        $output->writeln('注意不要禁用pcntl函数' . "\n");
        $action = $input->getArgument('action');
        global $argv;
        array_shift($argv);
        array_shift($argv);
        array_unshift($argv, 'think', $action);
        if ($action == 'start') {
            $output->writeln('Starting GatewayWorker Server...');
        }
        $this->start();
    }

    private function start()
    {
        new Register('text://0.0.0.0:' . config('extra.socket.register_port'));
        $gateway = new Gateway("websocket://0.0.0.0:" . config('extra.socket.websocket_port'));
        $gateway->name = 'gateway';
        $gateway->count = config('extra.socket.count');
        $gateway->lanIp = '127.0.0.1';
        $gateway->startPort = config('extra.socket.gateway_port');
        $gateway->registerAddress = '127.0.0.1:' . config('extra.socket.register_port');
        $gateway->pingInterval = 55;
        $gateway->pingData = '{"type":"ping"}';
        $worker = new BusinessWorker();
        $worker->name = 'businessworker';
        $worker->count = config('extra.socket.count');
        $worker->registerAddress = '127.0.0.1:' . config('extra.socket.register_port');
        $worker->eventHandler    = Events::class;
        Worker::$daemonize = config('extra.socket.daemonize');
        Worker::runAll();
    }
}
